package com.yonder.agenda.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Application context.
 * 
 * @author CosminS
 * @since Jan 28, 2014
 */
public class SpringApplicationContext implements ApplicationContextAware {
	/**
	 * Application context.
	 */
	private static ApplicationContext context;

	/**
	 * Constructor.
	 */
	public SpringApplicationContext() {
		super();
	}

	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		// done like this because it is considered bug to set static member from
		// instance method
		setContext(applicationContext);
	}

	private static void setContext(ApplicationContext applicationContext) {
		context = applicationContext;
	}

	/**
	 * Get application context.
	 * 
	 * @return ApplicationContext
	 */
	public static ApplicationContext getContext() {
		if (context == null) {
			context = new ClassPathXmlApplicationContext(
					"spring/spring-root.xml");
		}
		return context;
	}

	/**
	 * Get bean instance.
	 * 
	 * @param beanName
	 *            Bean name
	 * @return Bean instance
	 */
	public static Object getBean(String beanName) {
		return getContext().getBean(beanName);
	}

	/**
	 * Get bean instance.
	 * 
	 * @param clazz
	 *            Bean class definition
	 * @param <T>
	 *            return type
	 * @return Bean instance
	 */
	public static <T> T getBean(Class<T> clazz) {
		return getContext().getBean(clazz);
	}
}